//-------------------------------------------------------------------------------------------------
// author zhangwei on 2015.08.10
// modified by zhangwei on 2015.08.10
// - Released ver v1. This version is the clone from: https://github.com/TahaSh/Tasks-App-With-VueJS
//   And there's a good article about it: http://taha-sh.com/blog/many-js-frameworks-but-vuejs-is-different
// modified by zhangwei on 2015.08.10
// - Released ver 2. This is a readonly list.
// modified by zhangwei on 2015.08.28
// - Add grid component.
// modified by zhangwei on 2015.09
// - Add div switch to edit mode and setMode() support.
// modified by zhangwei in 2015.10
// - Released the UI and software architecture.
// - TODO: with backend rest interface
// modified by softstone in 2015.10
// - Add vue-grid (https://github.com/BastianHofmann/vue-grid)
// modified by softstone on 2015.10.21
// - Member CRUD passed.
// - Member edit improved.
// - Revised source code. Remove some unused code.
//
// Reference
// - http://taha-sh.com/blog/many-js-frameworks-but-vuejs-is-different
// - Html5's <template>, http://www.zhangxinxu.com/wordpress/2014/07/hello-html5-template-tag/
// - https://github.com/BastianHofmann/vue-grid/blob/master/vue-grid.js
// - https://github.com/bravf/VueUI/blob/master/src/vueUI.js
// - https://github.com/bravf/VueUI/blob/master/src/table/table.js
//
//-------------------------------------------------------------------------------------------------


// TODO on 2015.08.23
// - Uses vue-resource to fetch data from the backend or jQuery ajax to communicate with backend service.
// - Suggest use the standard code pattern in vue grid/table examples.
//   Better encapsulate the table as a component.


Array.removeRange = function(array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
};

function removeAt(array,idx)
{
        if(! Array.prototype.isPrototypeOf(array)){
            return null;//根据Null可以判断本次调用失败
        }
        var idx = parseInt(idx),
            iLen = idx.length;
        if(idx < 0 || idx >= iLen){
            return null;//根据Null可以判断本次调用失败
        }
        var aRet = [];//与NULL不同
        return aRet=array.slice(0,idx).concat(array.slice(idx+1));
}

/*
    VueUI.resetArray = function (a, b){
        while (a.length){
            a.pop()
        }
        b.forEach(function (x){
            a.push(x)
        })
    }
*/


// Application Service Used by the Vue Layer(View Layer)
var AppService = {

	//urlroot: "http://openwsn.tongji.edu.cn:8080/site/mvc/member/",
//	urlroot: "http://openwsn.tongji.edu.cn:8080/site/mvc/member/",
  urlroot: "http://localhost:8080/rest/sedt",
	init: function(){
		Vue.http.options.root = this.urlroot;
		//Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';
		//Vue.http.headers.common['ContentType'] = 'application/x-www-form-urlencoded';
	},

	newItem: function(){
		return newItem("0", true);
	},

	newItem: function(newid, newselected){
		var item = {
			id:newid,
			//rowid: null,
			owner: null,
			code: null,
			reluserid: 0,
			securitylevel: 0,
			idcard: null,
			firstname: "",
			midname: "",
			lastname: "",
			secname: "",
			nickname: "",
			respectname: "",
			gender: '*',
			email: "zhagnsan@163.com",
			mobilephone:"1373214421",
			im: "",
			qq: "",
			weixin: "",
			affiliation: "",
			employeeid: "",
			address: null,
			zip: null,
			birthday: null,
			sculpture: null,
			objectstate: null,
			rowstate: null,
			note: null,
			upduser: null,
			upddate: null,
			crtuser: null,
			crtdate: null,
			//
			node: '3211',
			selected: newselected,
			name:"zhang san",
			timestamp: '2015.07.08Z23:12:56:324:313',
			frame: '56 7F 2A 3D',
			title: 'Go to grocery store',
			completed: false
		};
		return item;
	},

	resetItem: function(item){
		item.id = null;
		item.owner = null;
		item.code = null;
		item.reluserid = 0;
		item.securitylevel = 0;
		item.idcard = null;
		item.firstname = "";
		item.midname = "";
		item.lastname = "";
		item.secname = "";
		item.nickname = "";
		item.respectname = "";
		item.gender = '-';
		item.email = "zhagnsan@163.com";
		item.mobilephone = "1373214421";
		item.im = "";
		item.qq = "";
		item.weixin = "";
		item.affiliation = "";
		item.employeeid = "";
		item.address = null;
		item.zip = null;
		item.birthday = null;
		item.sculpture = null;
		item.objectstate = null;
		item.rowstate = null;
		item.note = null;
		item.upduser = null;
		item.upddate = null;
		item.crtuser = null;
		item.crtdate = null;
		//
		item.selected = false;
		/*
			node: '3211',
			selected: newselected,
			name:"zhang san",
			timestamp: '2015.07.08Z23:12:56:324:313',
			frame: '56 7F 2A 3D',
			title: 'Go to grocery store',
			completed: false
		*/
	},

	// success(data, status, request)
	// error(data, status, request)
	find: function(inputQuery, pagenum, pagesteps, items, success_callback, error_callback){
		var url = this.urlroot;
		/*
		if (pagenum != null)
		{
			var tmparr = [this.urlroot, pagenum * pagesteps, '/', pagesteps];
			// url =  tmparr.join('');
			url = url + (pagenum*pagesteps) + '/' + pagesteps;
		}
		*/
		Vue.http.get(url, function(data, status, request){
			var i = data.length;
			success_callback(data, status, request);
		})
		.error(function (data, status, request) {
			alert("svc.find: fetch data from backend server failed! " + data + ' ' + status + ' ' + request);
			if (error_callback != null)
			{
				error_callback(data, status, request);
			}
		});
	},

	find2: function(inputQuery, pagenum, pagesteps, items, success_callback, error_callback){
		var url = this.urlroot;
		/*
			$.ajax({
				context: this,
				url: "/rest/istream",
                success: function (result) {
                	this.$set("items", result)
                }
            })
		*/
	},

	generate: function(inputQuery, pagenum, pagesteps, callback){
		var items = [];
		for (var i=0; i<pagesteps; i++)
		{
			items.push(this.newItem(i, (i % 2 == 0)));
		}
		if (typeof callabck == "function")
			callback(items);
	},

	/* get an item with its detail information from the backend server.
	 *
	 * Callback: function(item, status, request)
	 */
	get: function(id, callback){
		Vue.http.get(this.urlroot + this.id, callback);
     },

	getById: function(items, id){
		var result = null;
		var i = items.length;
		while (i--) {
			if (items[i].id == id)
			{
				result = items[i];
				break;
			}
		}
		return result;
	},

	indexof: function(items, id){
		var idx = null;
		var i = items.length;
		while (i--) {
			if (items[i].id == id)
			{
				idx = i;
				break;
			}
		}
		return i;
	},

	/* Update an item with its detail information to the backend server.
	 *
	 * Callback: function(item, status, request)
	 */
	set: function(id, item, success_callback, error_callback){
		// alert("svc.set " + item);
		// Vue.http.put({id:id}, {item:this.item}, success_callback).error(error_callback);

			$.ajax({
				data:JSON.stringify(item),
                type: "PUT",
                contentType: "application/json",
                url: "/site/mvc/member/" + item.id,

            })
	},

	add: function(item, success_callback, error_callback){
		var self = this;
		var result = null;
        $.ajax({
			// context: this,
			data:JSON.stringify(item),
            type: "POST",
            contentType: "application/json",
            url: "/site/mvc/member/",
             //user: self.user,
             //password: self.password,
             //async: false,
            success: function(response, textStatus){
				// The REST service should return the object id.
				// this.items.push(result);
                item.id = response.id;
                if (success_callback != null)
                {
					success_callback(response, textStatus);
                }
                result = response;
            },

            error: function(XMLHttpRequest, textStatus, errorThrown){
				//通常情况下textStatus和errorThrown只有其中一个包含信息
                //this;   //调用本次ajax请求时传递的options参数
                if (error_callback != null)
                {
					error_callback(XMLHttpRequest, textStatus, errorThrown);
                }
                result = null;
            }
        });

    	return result;
	},

	add2: function(item, success_callback, error_callback){
		// alert("svc.add " + item);

		/*Vue.http.post(this.urlroot, {
			data: JSON.stringify(item),
			method: "POST",
			params: item,
			success: success_callback,
			error: function(data, status, request){
				if (error_callback != null)
				{
					error_callback(data,status,request);
				}
			},
			timeout: 10
		});*/

		/* or the following code type?
		Vue.http.post(this.urlroot, item.stringify(), success_callback)
		.error(function(item, status, request){
			if (error_callback != null)
			{
				error_callback(item,status,request);
			}
		});
		*/
	},

    remove: function(item, success_callback, error_callback){
		//	Vue.http.delete({id:id}, success_callback).error(error_callback);
	    $.ajax({
			// context: '', //item,
            type: "DELETE",
            contentType: "application/json",
            url: "/site/mvc/member/" + item.id
        })
    },

    remove2: function(item, success_callback, error_callback){
		Vue.http.delete({id:id}, success_callback).error(error_callback);
    }
};


var svc = Object.create(AppService);

Vue.component('child', {
	props: ['myMessage'],
	template: '<span>通信录标题测试 <small>{{myMessage}}</small></span>'
});

// register modal component
Vue.component('itemeditor', {
	template: '#itemeditor-tpl',
	props:[{
			name: 'item',
			type: Object,
			twoWay: false,
			required: true
		},
		{
			name: 'mode',
			type: String,
			//default: 'modeList',
		},
		{
			name: 'onSubmit',
			type: Function,
			//required: true,
		},
		{
			name: 'onCancel',
			type: Function,
		},
	],

	data: function () {
        return {
			result: ''
        }
    },

	methods: {
		onSubmitClick: function(e){
			console.log("onSubmitClick: inside component itemeditor");
			this.result = this.onSubmit(this.mode, this.item);
		},
		onCancelClick: function(e){
			console.log("onCancelClick: inside component itemeditor");
			this.onCancel(this.mode, this.item);
		}
	},

	ready: function () {
		// this.onLoad('message from child!')
	}
});

// register modal component
Vue.component('modal', {
	template: '#modal-template',
	props: {
		show: {
			type: Boolean,
			required: true,
			twoWay: true
		}
	}
});

Vue.component('datatable', {
	template: '#datatable-tpl',
	props:[{
			name: 'tabledef',
			type: Object,
			twoWay: false,
			required: true
		},
		{
			name: 'onEdit',
			type: Function,
			//required: true,
		},
		{
			name: 'onRemove',
			type: Function,
		},
	],

	methods: {
  		onEditClick: function(item, e){
  			console.log('editItem: ' + item.id.toString());
  			//this.curitem = item;
			/*
			var detail = null;
  			svc.get({id: item.id}, function (detail, status, request) {
          		this.$set('curitem', detail)
     		});
			*/
			//this.setMode('modeEdit');
  		},

  		onRemoveClick: function(item, e){
  			console.log('removeItem' + item);
			//svc.remove(item);
            //this.items.$remove(item);
			//this.setMode('modeList');
  		},
	}

});

var vm = new Vue({
    el: '#app',

	data: {
		currentView: 'itemeditor',
		begintime: '',
		endtime: '',
		firstname: '',
		midname: '',
		lastname: '',
		remotedevice: '',
		searchQuery: '',

		tabledef: {
			isShowHeader: true,
		    isCheckable : true,
			columns : [
				{'field':'name', 'isSortable':true},
				'math',
				'chinese',
				{'field':'english', 'text':'英语', 'textAlign':'left','isSortable':true},
				'operate'
			],
			operations: [
				{
					label: '删除',
					action: Function
				},
				{
					label: '编辑',
					action: Function
				}
			],
			items: [
				{ id:'fsfa',rowid: 3, selected: true, firstname:'wang01',timestamp: '2015.07.08Z23:12:56:324:313', node: '3213121', frame: '56 7F 2A 3D', title: 'Go to grocery store', completed: false },
				{ id: 'abc', rowid: 4, selected: false, firstname:'wang02',timestamp: '2015.07.08Z23:12:56:325:313', node: '3213121', frame: '56 7F 2A 3D', title: 'Go to grocery store', completed: false },
				{ id: 'ad', rowid: 5, selected: true, firstname:'wang03',timestamp: '2015.07.08Z23:12:56:327:313', node: '3213123', frame: '56 7F 2A 3D', title: 'Go to grocery store', completed: false },
			],
			onPagerChange : function (num){
				getData(num)
			},
			onSortChange : function (field, dir){
				console.log(field)
				console.log(dir)
			}
		},

        items: [
            //{ rowid: 3, selected: true, firstname:'wang01',timestamp: '2015.07.08Z23:12:56:324:313', node: '3213121', frame: '56 7F 2A 3D', title: 'Go to grocery store', completed: false },
            //{ rowid: 4, selected: false, firstname:'wang02',timestamp: '2015.07.08Z23:12:56:325:313', node: '3213121', frame: '56 7F 2A 3D', title: 'Go to grocery store', completed: false },
            //{ rowid: 5, selected: true, firstname:'wang03',timestamp: '2015.07.08Z23:12:56:327:313', node: '3213123', frame: '56 7F 2A 3D', title: 'Go to grocery store', completed: false },
        ],
		curitem: {},

		selectall: true,
		mode: 'modeList', // modeList, modeItemView, modeAddNew, modeEdit
		modeTitle: "",



		showModal: false,
		parentMsg: "test",
		curdate: "2015.10.07",

		gridColumns: ['name', 'age'],
		gridData: [
			{ name: 'Barack Obama', age: 53 },
			{ name: 'Some Dude', age: 24 },
			{ name: 'Tv Dude', age: 28 },
			{ name: 'Ice Dude', age: 34 },
			{ name: 'Mel Dude', age: 25 },
			{ name: 'Word Dude', age: 29 },
			{ name: 'Even Dude', age: 44 },
			{ name: 'More Dude', age: 54 },
			{ name: 'Thor Dude', age: 29 },
			{ name: 'Noel Dude', age: 26 },
			{ name: 'Tiffany Dude', age: 14 },
			{ name: 'Miranda Dude', age: 28 },
			{ name: 'Jeff Dude', age: 23 },
			{ name: 'Jack Dude', age: 54 },
			{ name: 'Jimmy Dude', age: 44 },
			{ name: 'Jon Dude', age: 34 },
			{ name: 'Another Dude', age: 34 }
		],
	},

	components: {
		//list: { /* ... */ },
		//itemviewer: { /* ... */ },
		//itemeditor: itemeditor,
	},

	methods: {
		__find: function(inputQuery, pagenum, pagesteps){
			var self = this;
			svc.find('', pagenum, pagesteps, this.items, function(data, status, request){
				// self.items.length = 0;
				self.$set('items', data);
				if (self.items.length > 0)
				{
					self.$set("curitem", self.items[0]);
				}
				// alert("vm.init: items.length = " + self.items.length);
				// alert(JSON.stringify(self.items));
			}, function(data, status, request){
				alert("Probably failed to connect the backend server! Pls check your server status!");
			});
		},

		init: function(){
			svc.init();
			// this.__find('', 1, 6);

			var datetime = new Date();
			datetime.getYear();        //获取当前年份(2位)
			datetime.getFullYear();    //获取完整的年份(4位,1970-????)
			datetime.getMonth();       //获取当前月份(0-11,0代表1月)
			datetime.getDate();        //获取当前日(1-31)
			datetime.getDay();         //获取当前星期X(0-6,0代表星期天)
			datetime.getTime();        //获取当前时间(从1970.1.1开始的毫秒数)
			datetime.getHours();       //获取当前小时数(0-23)
			datetime.getMinutes();     //获取当前分钟数(0-59)
			datetime.getSeconds();     //获取当前秒数(0-59)
			datetime.getMilliseconds();    //获取当前毫秒数(0-999)
			datetime.toLocaleDateString();     //获取当前日期
			this.curdate = datetime.toLocaleTimeString();     //获取当前时间
		},

		basicsearch: function(e){
			this.searchQuery = this.searchQuery.trim();
			if ((this.searchQuery).length == 0 )
			{
				document.getElementById("searchQuery").focus();
				alert("Please input search query");
			}
			this.__find(this.searchQuery, 1, 5);
		},

		advancedsearch: function(e){
			console.log("advanced search");
			console.log(e.target.tagName); // "BUTTON"
			console.log(e.targetVM === this); // true

			var inputs = new Array();
			inputs[0] = "{begintime:'";
			inputs[1] = this.begintime;
			inputs[2] = "', endtime:'";
			inputs[3] = this.endtime;
			inputs[4] = "', remotedevice:'";
			inputs[5] = this.remotedevice;
			inputs[6] = "', searchQuery:'";
			inputs[7] = this.searchQuery;
			inputs[8] = "'}";

			var inputQuery = inputs.join('');
			console.log("your input query condition is " + inputQuery);
			this.__find(inputQuery, 2, 5);
		},

		/*
		_findxxx: function(vm, inputQuery, pagenumber, pagesteps){
			setTimeout(function(){
				svc.find(inputQuery, 1, 6, function(data){
					vm.$set('items', data);
				});
			}, 20);
		    setTimeout(function (){
				var data =  svc.find(pagenumber, pagesteps);
				var tmplen = vm.items.length;
				for (var i=0; i<pagesteps; i++)
				{
					data[i].rowid = tmplen + i;
					//vm.items.push(data[i]);
				}
				vm.$set('items', data);
		    }, 100)
		},
		*/

		/*
        clearData : function (){
			console.log("clear button");
            var myTable = VueUI.getComponent('myTable')
            VueUI.resetArray(tableConf.data, [])
            //tableConf.data = []
            //tableConf.data = []
            //myTable.data = []
            myTable.totalPage = 0
            myTable.totalCount = 0
        }
		*/

		onSave: function(mode,item){
			var self = this;
			console.log("onSave");
			if (mode == 'modeAddNew')
			{
				svc.add(item, function(response, textStatus){
					// alert("onSave add success");
					// item.id = response.id;
					// self.items.push(response);
					// vm.items.$set(vm.items.length, response);
					// vm.$add(this.items[...], item);
					self.__find('', 1, 6);
					// self.setMode('modeList');
				}, null);
			}
			else{
				svc.set(item.id, item, function(item, status, request){
					var idx = svc.indexof(this.items, item.id);
					if (idx != null)
					{
						vm.$set(this.items[idx], item);
					}
					// self.setMode('modeList');
				}, function(item, status, request){
					alert("onSave failed to update!");
				});
			}

			setTimeout(function (){
				self.setMode('modeList');
			}, 20);
		},

		onCancel: function(mode,item){
			console.log("onCancel");
			this.setMode('modeList');
		},

		//sortBy: function (key) {
		//	this.sortKey = key
		//	this.reversed[key] = !this.reversed[key]
		//}

        // TODO: test with backend
  		onEdit: function(item, e){
  			console.log('editItem: ' + item.id.toString());
  			this.curitem = item;
			/*
			var detail = null;
  			svc.get({id: item.id}, function (detail, status, request) {
          		this.$set('curitem', detail)
     		});
			*/
			this.setMode('modeEdit');
  		},

  		onRemoveItem: function(item, e){
  			console.log('removeItem' + item);
			svc.remove(item);
            this.items.$remove(item);
			this.setMode('modeList');
  		},

		// delete each item according to the item.selected property
		onRemoveSelected: function(e){
			console.log("removeSelected: " + e);
			var items = this.items;
			for (var i in items){
				if (items[i].selected)
				{
					console.log(items[i] + ' is to be deleted!!!');
					this.onRemoveItem(items[i], null);
				}
			}
		},

		setMode: function(newmode){
			if (this.mode != newmode)
			{
				this.mode = newmode;
				switch (newmode)
				{
				case "modeList":
					this.modeTitle = "";
					break;
				case "modeItemView":
					this.modeTitle = " [详情]";
					break;
				case "modeEdit":
					this.modeTitle = " [编辑]";
					break;
				case "modeAddNew":
					this.modeTitle = " [新增]";
					//this.curitem.id=null;
					resetItem(this.curitem);
					this.curitem.id=null;
					break;
				default:
					this.modeTitle = "";
				}
			}
		},

		getGender: function(value){
			var ret = '-';
			if (this.value == 'M')
				ret = '男';
			else if (this.value == 'F')
				ret = '女';
			return ret;
		}
	},

	ready: function(){
		// console.log("ready function is called");
		this.__find('', 1, 6);
	}
});

setTimeout(function (){
	vm.init();
}, 20);

// equvalent to $(document).ready(function(){...}
$(function () {
});




